package com.idea.zd.sys.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


public class SysUtil {
	private static long currentId = 0;
	private static char serverId;
	private static Object idLock = new Object();

	

	private static char intToChar(int val) {
		if (val < 10)
			return (char) (val + 48);
		else
			return (char) (val + 55);
	}

	public static int isToOs(InputStream is, OutputStream os) throws Exception {
		byte buf[] = new byte[8192];
		int len, size = 0;

		while ((len = is.read(buf)) > 0) {
			os.write(buf, 0, len);
			size += len;
		}
		return size;
	}
	private static String numToString(long num) {
		char[] buf = new char[12];
		int charPos = 12;
		long val;

		buf[0] = serverId;
		while ((val = num / 36) > 0) {
			buf[--charPos] = intToChar((int) (num % 36));
			num = val;
		}
		buf[--charPos] = intToChar((int) (num % 36));
		return new String(buf);
	}


	public static void executeMethod(String classMethodName,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int pos = classMethodName.lastIndexOf('.');
		String className, methodName;

		if (pos == -1) {
			className = "";
			methodName = classMethodName;
		} else {
			className = classMethodName.substring(0, pos);
			methodName = classMethodName.substring(pos + 1);
		}
		Class<?> cls = Class.forName(className);
		cls.getMethod(methodName, HttpServletRequest.class,
				HttpServletResponse.class).invoke(cls, request, response);
	}

	

	
	public static String readString(Reader reader) throws Exception {
		char buf[] = new char[8192];
		StringBuilder sb = new StringBuilder();
		int len;

		while ((len = reader.read(buf)) > 0) {
			sb.append(buf, 0, len);
		}
		return sb.toString();
	}

	public static void closeInputStream(InputStream inputStream) {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (Throwable e) {
			}
		}
	}

	public static void error(String msg) throws Exception {
		throw new Exception(msg);
	}
	
	/**
	 * UID生成器
	 * @return
	 * @throws Exception
	 */
	public static String getUUID(){
		String uid=UUID.randomUUID().toString();
		return uid.replace("-", ""); 
	}
	
	public static String setNumber(String type,String num){
		if(type.equals("01")){
			return "第"+num+"期";
		}else if(type.equals("02")){
			return "第"+num+"集";
		}
	    return null;
	}
	
	public static String setWeek(int week){
		switch(week){
		case 1:
			return "周一";
		case 2:
			return "周二";
		case 3:
			return "周三";
		case 4:
			return "周四";
		case 5:
			return "周五";
		case 6:
			return "周六";
		case 7:
			return "周日";
		}
		return null;
	}
	
	public static String getWeekOfDate(Date date) {      
	    String[] weekOfDays = {"7", "1", "2", "3", "4", "5", "6"};        
	    Calendar calendar = Calendar.getInstance();      
	    if(date != null){        
	         calendar.setTime(date);      
	    }        
	    int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;      
	    if (w < 0){        
	        w = 0;      
	    }      
	    return weekOfDays[w];    
	}
	
	public static String getDateTime() {      
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return simpleDateFormat.format(new Date());  
	}
	
	public static String getDate() {      
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return simpleDateFormat.format(new Date());  
	}
	
	public static String getFormatDate(String date,String dateFormat) throws ParseException{
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dateTime = simpleDateFormat.parse(date);
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		System.out.println(sdf.format(dateTime).toString());
		return sdf.format(dateTime);
	}
	
	/**
	 * 字符串日期格式
	 * @param date
	 * @param dateFormat
	 * @return
	 */
	public static String getFormatDate(Date date,String dateFormat){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
		return simpleDateFormat.format(date);
	}
	
	public static Long getTimeStamp(String date) throws ParseException{
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dateTime = simpleDateFormat.parse(date);
		return  dateTime.getTime();
	}
	
	
	
	public static int getTotalPage(int totalCount,int pageSize){
		
		if(totalCount<1){
			return 1;
		}
		return totalCount%pageSize>0?totalCount/pageSize+1:totalCount/pageSize;
	}
	
	public static String getReturnString(String  Str){
		
		if(Str == null || Str.equals("")){
			return "";
		}
		return Str;
	}
	
	public static String getBoolean(String flag){
		
		if("0".equals(flag)){
			return "false";
		}
		return "true";
	}
	public static String getRandomString(int length) { //length表示生成字符串的长度
	    String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	 }
	
	public static String getRandomHeadPic() { 
		String[] images={"random_head_pic/01.png","random_head_pic/02.png","random_head_pic/03.png","random_head_pic/04.png","random_head_pic/05.png","random_head_pic/06.png","random_head_pic/07.png","random_head_pic/08.png","random_head_pic/09.png","random_head_pic/10.png","random_head_pic/11.png","random_head_pic/12.png"};
	    Random random = new Random();   
	    int i=random.nextInt(11);
	    return images[i];   
	 }
	public static String getProgram(String programType){
		String str = "";
		if(programType.equals("0")){
			str = "个人";
		}else if(programType.equals("1")){
			str = "living";
		}else if(programType.equals("2")){
			str = "帖子";
		}
		return str;
	}
	public static String filter(String word){
		String str = word;
		List<Record> list = Db.find("select * from fsj_key_word where is_disable=0 ");
		for(Record r : list){
			if(str.equals(r.get("key_word"))){
				String rep_str="";
				for(int i=0;i<str.length();i++){
					rep_str+="*";
				}
				str=str.replaceAll(word, rep_str);
			}
		}
		return str;
	}
	
	
	
	
	public static int getWeek(String week){
		String playWeek = "";
		String [] weeks;
		String curWeek = SysUtil.getWeekOfDate(new Date());
		
		if(week.indexOf(",") !=-1){
			weeks = week.split(",");
			
			if(Integer.parseInt(curWeek) > Integer.parseInt(weeks[weeks.length-1])){
				playWeek = weeks[0];
			}else{
				for(int i = 0; i < weeks.length; i++){
					
					if(curWeek.equals(weeks[i])){
						playWeek = weeks[i];
						break;
					}
					
				}
				
				if(StrKit.isBlank(playWeek)){
					
						for(int i = 0; i < weeks.length; i++){
							
							if(Integer.parseInt(curWeek) > Integer.parseInt(weeks[i]) && (Integer.parseInt(curWeek) < Integer.parseInt(weeks[i+1]))){
								playWeek = weeks[i+1];
								break;
							}
						}
				}
			}
			
			
		}else{
			playWeek = week;
		}
		return Integer.parseInt(playWeek);
	}
	
	
	
	/**
	 * 验证是否为空
	 * @param object
	 * @return
	 */
	public static String validateStr(Object object){
		
		if(null == object){
			return "";
		}else{
			return object.toString();
		}
	}
	
	
	
	public static void main(String[] args) throws ParseException {
		//System.out.println(new Date().getTime());
		//System.out.println(SysUtil.getTimeStamp("2015-11-18 11:30:00").toString());
	}
}
